/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package presenter;

import database.BusinessDelegate;
import database.Message;
import database.Profile;
import static database.Profile.Status.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author root
 */
public class Presenter {

    public static final String PATH = "/root/NetBeansProjects/BeSopra/trunk/mis-system/src/File/";
    //public static final String PATH = "/";
    
//will call a business delegate's method
    public static boolean checkProfile(String login, String password) {
        boolean result = BusinessDelegate.correctPassword(login, password);
        Profile p = BusinessDelegate.getProfile(login);
        if (result) {
            BusinessDelegate.incrementNbConnections(p);
        }
        return result;

    }

    //will call a business delegate's method
    public static ArrayList<String> getContactList(String login) {
        return BusinessDelegate.getContactList(BusinessDelegate.getProfile(login));
    }

    public static boolean isAdmin(String login) {
        /*if (login.equals("admin")){
         return true;
         }
         else 
         return false;*/
        return BusinessDelegate.isAdmin(BusinessDelegate.getProfile(login));
    }

    public static Map<String, String> searchContact(String search, String type) {
        Map<String, String> results = new HashMap<>();
        ArrayList<String> list;
        switch (type) {
            case "login":
                list = BusinessDelegate.searchContactByLogin(search);
                for (String s : list) {
                    results.put(s, BusinessDelegate.getProfile(s).getEmail());
                }
                break;
            case "name":
                list = BusinessDelegate.searchContactByLastName(search);
                for (String s : list) {
                    results.put(s, BusinessDelegate.getProfile(s).getEmail());
                }
                break;
            case "mail":
                list = BusinessDelegate.searchContactByEmail(search);
                for (String s : list) {
                    results.put(s, BusinessDelegate.getProfile(s).getEmail());
                }
                break;
        }
        return results;
    }

    public static String createAccount(String firstname, String lastname, String pwd, String rights, String email) {
        Profile profile;
        if (rights.equals("admin")) {
            profile = new Profile(firstname, lastname, pwd, email, true);
        } else {
            profile = new Profile(firstname, lastname, pwd, email, false);
        }
        BusinessDelegate.insertProfile(profile);
        return profile.getLogin();
    }

    public static void deleteAccount(String login) {
        BusinessDelegate.deleteProfile(BusinessDelegate.getProfile(login));
    }

    public static void addContact(String login1, String login2) {
        Profile profile1 = BusinessDelegate.getProfile(login1);
        Profile profile2 = BusinessDelegate.getProfile(login2);
        BusinessDelegate.acceptFriendship(profile1, profile2);
    }

    public static void deleteContact(String login1, String login2) {
        Profile profile1 = BusinessDelegate.getProfile(login1);
        Profile profile2 = BusinessDelegate.getProfile(login2);
        BusinessDelegate.deleteFriendship(profile1, profile2);
    }

    public static String getLname(String login) {
        return BusinessDelegate.getProfile(login).getLastName();
    }

    public static String getFname(String login) {
        return BusinessDelegate.getProfile(login).getFirstName();
    }

    public static String getEmail(String login) {
        return BusinessDelegate.getProfile(login).getEmail();
    }

    public static void setPassword(String login, String password) {
        Profile profile = BusinessDelegate.getProfile(login);
        BusinessDelegate.setPassword(profile, password);
    }

    public static void setStatus(String login, String status) {
        Profile.Status pstatus;
        Profile profile = BusinessDelegate.getProfile(login);
        switch (status) {
            case "Disconnected":
                pstatus = DISCONNECTED;
                break;
            case "Connected":
                pstatus = CONNECTED;
                break;
            case "Busy":
                pstatus = BUSY;
                break;
            case "Away":
                pstatus = AWAY;
                break;
            default:
                pstatus = DISCONNECTED;
        }
        BusinessDelegate.setStatus(profile, pstatus);
    }

    public static String getStatus(String login) {
        String status;
        Profile profile = BusinessDelegate.getProfile(login);
        switch (profile.getStatus()) {
            case DISCONNECTED:
                status = "Disc";
                break;
            case CONNECTED:
                status = "Connect";
                break;
            case BUSY:
                status = "Busy";
                break;
            case AWAY:
                status = "Away";
                break;
            default:
                status = "Disc";
        }
        return status;
    }

    public static String getStatusIconAddr(String login) {
        String addr;
        Profile profile = BusinessDelegate.getProfile(login);
        switch (profile.getStatus()) {
            case DISCONNECTED:
                addr = "offline.png";
                break;
            case CONNECTED:
                addr = "online.png";
                break;
            case BUSY:
                addr = "busy.png";
                break;
            case AWAY:
                addr = "away.png";
                break;
            default:
                addr = "offline.png";
        }
        return addr;
    }

    public static String getStatusIconAddrBig(String login) {
        String addr;
        Profile profile = BusinessDelegate.getProfile(login);
        switch (profile.getStatus()) {
            case DISCONNECTED:
                addr = "offline256x256.png";
                break;
            case CONNECTED:
                addr = "online256x256.png";
                break;
            case BUSY:
                addr = "busy256x256.png";
                break;
            case AWAY:
                addr = "away256x256.png";
                break;
            default:
                addr = "offline256x256.png";
        }
        return addr;
    }

    public static void saveMessage(String sender, String receiver, String txt) {
        Profile psender = BusinessDelegate.getProfile(sender);
        Profile preceiver = BusinessDelegate.getProfile(receiver);
        Profile.Status sreceiver = preceiver.getStatus();
        Message msg;
        if (sreceiver != DISCONNECTED) {
            msg = new Message(psender, preceiver, txt, true);
        } else {
            msg = new Message(psender, preceiver, txt, false);
        }
        BusinessDelegate.insertMessage(msg);
    }

    public static void setIsAdmin(String login, boolean isAdmin) {
        Profile p = BusinessDelegate.getProfile(login);
        BusinessDelegate.setAdmin(p, isAdmin);
    }

    public static Map<String, String> getUnreadMsg(String login1) {
        Map<String, String> unreadMsg = new HashMap<>();
        Profile profile1 = BusinessDelegate.getProfile(login1);
        Profile profile2;
        ArrayList<String> contacts = BusinessDelegate.getContactList(profile1);
        ArrayList<Message> messages;
        String longMsg;
        for (String contact : contacts) {
            profile2 = BusinessDelegate.getProfile(contact);
            longMsg = "";
            messages = BusinessDelegate.getUndeliveredConversation(profile1, profile2);
            if (!messages.isEmpty()) {
                for (Message msg : messages) {
                    if (msg.getReceiver() == profile1) {
                        longMsg = longMsg + contact + " (" + msg.getDateMsg() + " : " + msg.getTimeMsg() + "): " + msg.getText() + "<br>";
                        unreadMsg.put(contact, longMsg);
                    }
                }
            }
        }

        return unreadMsg;
    }

    public static void addContactDemand(String demander, String receiver) {
        Profile pdemander = BusinessDelegate.getProfile(demander);
        Profile preceiver = BusinessDelegate.getProfile(receiver);
        BusinessDelegate.insertPendingFriendship(pdemander, preceiver);
    }

    public static ArrayList<String> getContactDemand(String login) {
        Profile p = BusinessDelegate.getProfile(login);
        return BusinessDelegate.getPendingFriendship(p);
    }

    public static void saveFile(String login, String dest, java.io.File myFile) {
        String name = null;
        Profile pLogin = BusinessDelegate.getProfile(login);
        Profile pDest = BusinessDelegate.getProfile(dest);
        String path = myFile.getPath();
        System.out.println("path: " + path);
        database.File dFile = new database.File(path, pLogin, pDest);
        name = BusinessDelegate.insertFile(dFile);
        name = myFile.getParent() + "/" + name;
        System.out.println("name: " + name);
        myFile.renameTo(new java.io.File(name));
    }

    public static HashMap<String, String> getWaitingFile(String login) {
        HashMap<String, String> files = new HashMap<String, String>();
        Profile p = BusinessDelegate.getProfile(login);
        String slogin;
        ArrayList<database.File> lFiles = BusinessDelegate.getFilesNotDownloaded(p);
        for (database.File f : lFiles) {
            slogin = f.getSender().getLogin();
            files.put(f.getName(), slogin);
        }
        return files;
    }

    public static HashMap<String, String> getFiles(String login) {
        HashMap<String, String> files = new HashMap<String, String>();
        String slogin;
        Profile p = BusinessDelegate.getProfile(login);
        ArrayList<database.File> lFiles = BusinessDelegate.getAllFiles(p);
        for (database.File f : lFiles) {
            slogin = f.getSender().getLogin();
            files.put(f.getName(), slogin);
        }
        return files;
    }

    public static void setDownloaded(String login) {
        Profile p = BusinessDelegate.getProfile(login);
        BusinessDelegate.setAllFilesDownloaded(p);
    }

    public static String getTotalConversation(String login1, String login2) {
        FileWriter fw = null;
        File conv = null;
        String result = "";
        try {
            Profile p1 = BusinessDelegate.getProfile(login1);
            Profile p2 = BusinessDelegate.getProfile(login2);
            ArrayList<Message> messagesl = BusinessDelegate.getAllConversation(p1, p2);
            
            conv = new File(PATH + File.separator + "conversation_" + login1 + "_" + login2 + ".txt");
            if (conv.exists()) {
                conv.delete();
                conv = new File(PATH + File.separator + "conversation_" + login1 + "_" + login2 + ".txt");
            }

            fw = new FileWriter(conv.getPath(), true);
            BufferedWriter out = new BufferedWriter(fw);

            for (Message m : messagesl) {
                out.write(m.getSender().getLogin() + ">" + m.getReceiver().getLogin() + " (" + m.getDateMsg() + " : " + m.getTimeMsg() + "): " + m.getText() + "\n");
                out.flush();
            }

        } catch (IOException ex) {
            Logger.getLogger(Presenter.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fw.close();
                result = conv.getName();
            } catch (IOException ex) {
                Logger.getLogger(Presenter.class.getName()).log(Level.SEVERE, null, ex);
            }
            return result;
        }
    }

    public static int getNbConnections() {
        return BusinessDelegate.getNbConnections();
    }

    public static int getNbProfiles() {
        return BusinessDelegate.getNbProfiles();
    }

    public static int getNbMessages() {
        return BusinessDelegate.getNbMessages();
    }

    public static int getNbFiles() {
        return BusinessDelegate.getNbFiles();
    }
}
